/**
 * 审批流程实例 列表页 JS 脚本
 * @author 李方捷 , leefangjie@qq.com
 * @since 2023-04-19 10:29:06
 * @version 2023-04-19
 */

layui.config({
    dir: layuiPath,
    base: '/module/'
}).extend({
    xmSelect: 'xm-select/xm-select',
    foxnicUpload: 'upload/foxnic-upload'
});
//
layui.define(['form', 'table', 'util', 'settings', 'admin', 'upload','foxnic','xmSelect','laydate','foxnicUpload','dropdown','bpm'],function () {

    var admin = layui.admin,settings = layui.settings,form = layui.form,upload = layui.upload,laydate= layui.laydate,dropdown=layui.dropdown;
    table = layui.table,layer = layui.layer,util = layui.util,fox = layui.foxnic,xmSelect = layui.xmSelect,foxup=layui.foxnicUpload,bpm=layui.bpm;

    //模块基础路径
    const moduleURL="/service-patent/pat-patent-process";

    var processId=QueryString.get("processId");
    var processInstance=null;

    //列表页的扩展
    var list={
        /**
         * 列表页初始化前调用
         * */
        beforeInit:function () {
            console.log("list:beforeInit");
        },
        /**
         * 按事件名称移除表格按钮栏的按钮
         * */
        removeOperationButtonByEvent(event) {
            var template=$("#tableOperationTemplate");
            var content=template.text();
            content=content.split("\n");
            var buttons=[]
            for (let i = 0; i < content.length ; i++) {
                if(content[i] && content[i].indexOf("lay-event=\""+event+"\"")==-1) {
                    buttons.push(content[i]);
                }
            }
            template.text(buttons.join("\n"))
        },
        /**
         * 表格渲染前调用
         * @param cfg 表格配置参数
         * */
        beforeTableRender:function (cfg){
            console.log("list:beforeTableRender",cfg);
        },
        /**
         * 表格渲染后调用
         * */
        afterTableRender :function (){


        },
        afterSearchInputReady: function() {
            console.log("list:afterSearchInputReady");
        },
        /**
         * 对话框打开之前调用，如果返回 null 则不打开对话框
         * */
        beforeDialog:function (param){
            //param.title="覆盖对话框标题";
            return param;
        },
        /**
         * 对话框回调，表单域以及按钮 会自动改变为选中的值，此处处理额外的逻辑即可
         * */
        afterDialog:function (param,result) {
            console.log('dialog',param,result);
        },
        /**
         * 当下拉框别选择后触发
         * */
        onSelectBoxChanged:function(id,selected,changes,isAdd) {
            console.log('onSelectBoxChanged',id,selected,changes,isAdd);
        },
        /**
         * 当日期选择组件选择后触发
         * */
        onDatePickerChanged:function(id,value, date, endDate) {
            console.log('onDatePickerChanged',id,value, date, endDate);
        },
        /**
         * 查询前调用
         * @param conditions 复合查询条件
         * @param param 请求参数
         * @param location 调用的代码位置
         * */
        beforeQuery:function (conditions,param,location) {
            console.log('beforeQuery',conditions,param,location);
            return true;
        },
        /**
         * 查询结果渲染后调用
         * */
        afterQuery : function (data) {
            var sw=$(".layui-form-switch")
            var el=sw.parent().find("input");
            el.attr("readonly", "yes");
            el.attr("disabled", "yes");

            sw.addClass("layui-disabled");
            sw.addClass("layui-checkbox-disabled");
            sw.addClass("layui-form-switch-disabled");
        },
        afterRefreshRowData:function(data,remote) {
            this.afterQuery(data);
        },
        /**
         * 进一步转换 list 数据
         * */
        templet:function (field,value,r) {
            if(value==null) return "";
            return value;
        },
        /**
         * 表单页面打开时，追加更多的参数信息
         * */
        makeFormQueryString:function(data,queryString,action) {
            return queryString;
        },
        /**
         * 新建流程时返回流程表单需要预填的默认值  act : create/edit
         * */
        getBpmViewConfig:function (act) {
            return {
                title:"这是默认标题",
                priority:"normal", // priority 的可选值 urgency，normal
                labelWidth:108, // 标签宽度，用于对齐
                displayTitle:true,  // 是否显示标题与优先级
                displayPriority:false, // 是否显示优先级
                displayDraftComment:false, // 是否显示起草节点的流程说明
                displayApprovalAttachment:true,
                displayApprovalComment:true // 是否显示签字意见
            }
        },
        /**
         * 表单没有关联的流程时的处理逻辑
         * */
        handleNoProcessBill:function(idValue) {
            top.layer.msg('当前业务单据尚未关联流程', {icon: 2, time: 1500});
        },
        /**
         * 在新建或编辑窗口打开前调用，若返回 false 则不继续执行后续操作
         * */
        beforeEdit:function (data) {
            console.log('beforeEdit',data);
            return true;
        },
        /**
         * 单行删除前调用，若返回false则不执行后续操作
         * */
        beforeSingleDelete:function (data) {
            console.log('beforeSingleDelete',data);
            return true;
        },
        afterSingleDelete:function (data){
            console.log('beforeSingleDelete',data);
            return true;
        },
        /**
         * 批量删除前调用，若返回false则不执行后续操作
         * */
        beforeBatchDelete:function (selected) {
            console.log('beforeBatchDelete',selected);
            return true;
        },
        /**
         * 批量删除后调用，若返回false则不执行后续操作
         * */
        afterBatchDelete:function (data) {
            console.log('afterBatchDelete',data);
            return true;
        },
        /**
         * 工具栏按钮事件前调用，如果返回 false 则不执行后续代码
         * */
        beforeToolBarButtonEvent:function (selected,obj) {
            console.log('beforeToolBarButtonEvent',selected,obj);
            return true;
        },
        /**
         * 列表操作栏按钮事件前调用，如果返回 false 则不执行后续代码
         * */
        beforeRowOperationEvent:function (data,obj) {
            console.log('beforeRowOperationEvent',data,obj);
            return true;
        },
        /**
         * 表格右侧操作列更多按钮事件
         * */
        moreAction:function (menu,data, it){
            console.log('moreAction',menu,data,it);
        },
        /**
         * 末尾执行
         */
        ending:function() {

        }
    }

    // 视图配置
    var FORM_VIEW={
        // status:{
        //     display:true,
        //     readonly:true
        // },
        // 案件代理人
        caseAgentIds: {
            display:["N1","N2","N3","N6","N7","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N1 , 其它全部只读
                // debugger
                return nodeId!="N1" && nodeId!="N7";
            }
        },

        // 外协人员
        outPersonIds: {
            display:["N1","N2","N3","N6","N7","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N1 , 其它全部只读
                // debugger
                return nodeId!="N1";
            }
        },

        // 商务助理
        businessAssistantIds: {
            display:["N1","N2","N3","N6","N7","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N1 , 其它全部只读
                // debugger
                return nodeId!="N1" && nodeId!="N15";
            }
        },

        // 案件类型
        subtype: {
            display:["N1","N2","N3","N6","N7","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N1 , 其它全部只读
                // debugger
                return nodeId!="N1";
            },
            selector:function () {
                return $("[name=subtype]");
            }
        },

        // 是否交底
        isGotBase: {
            display:["N1","N2","N3","N6","N7","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N1 , 其它全部只读
                // debugger
                return nodeId!="N1";
            }
        },
        // 是否检索
        retrieval: {
            display:["N1","N2","N3","N6","N7","N10","N11","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N1 , 其它全部只读
                // debugger
                return nodeId!="N1";
            }
        },
        // 无交底继续
        noBaseContinue: {
            display:["N3"],
            readonly:function (nodeId) {
                // 如果不是 N3 , 其它全部只读
                return nodeId!="N3";
            }
        },
        // 事务所能否完成
        canOfficeDone: {
            display:["N7","N10","N11","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N7 , 其它全部只读
                return nodeId!="N7";
            }
        },
        // 材料是否齐全
        isMaterialComplete: {
            display:function (nodeId,data) {
                if(nodeId=="N2") {
                    if(data.isMaterialComplete) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    var nodeIds=["N7","N10","N12","N13","N14","N15","N16","N17","N18","N19","N20","N21"];
                    return nodeIds.indexOf(nodeId)!=-1;
                }

            },
            readonly:function (nodeId) {
                // 如果不是 N7 , 其它全部只读
                return nodeId!="N7" && nodeId!="N12";
            }
        },
        // 代理能否完成
        canAgentDone: {
            display:["N7","N10","N11","N14","N15","N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N7 , 其它全部只读
                return nodeId!="N7";
            }
        },
        // 是否定稿
        finalized: {
            display:["N16","N17","N18","N19","N20","N21"],
            readonly:function (nodeId) {
                // 如果不是 N7 , 其它全部只读
                return nodeId!="N16";
            }
        }

    };

    //表单页的扩展
    var form={
        /**
         * 表单初始化前调用 , 并传入表单数据
         * */
        beforeInit:function (action,data) {
            //获取参数，并调整下拉框查询用的URL
            //var companyId=admin.getTempData("companyId");
            //fox.setSelectBoxUrl("employeeId","/service-hrm/hrm-employee/query-paged-list?companyId="+companyId);
            console.log("form:beforeInit")
            // this.hideAllFormItems();
            layui.form.on('switch(isGotBase)', function (obj) {
                var data=window.module.getFormData();
                var value=data.isGotBase;
                if(value=="1") {
                    $("#caseAgentIds").parents(".layui-form-item").show();
                    $("#outPersonIds").parents(".layui-form-item").hide();
                } else {
                    $("#caseAgentIds").parents(".layui-form-item").hide();
                    $("#outPersonIds").parents(".layui-form-item").show();
                }
            });


        },
        hideAllFormItems() {
            for(var field in FORM_VIEW) {
                // debugger
                $("#" + field).parents(".layui-form-item").hide();
                this.disabledInputs.push($("#" + field).attr("name"));
            }
        },
        openRemindSettingWindow:function (data,button,el) {
            debugger
            var todoNodes=bpm.getTodoNodes(processInstance);
            if(todoNodes==null || todoNodes.length==0) return;
            admin.putVar("remindParams",{id:data.id,sourceNodeId:todoNodes[0].camundaNodeId});
            admin.popupCenter({
                title: "设置流程提醒",
                resize: false,
                offset: [],
                area: ["800px","80%"],
                type: 2,
                id:"patent_remind_list_win",
                content: 'public/business/patent/patent_remind/patent_remind_list.html',
                finish: function () {

                }
            });
        },
        /**
         * 窗口调节前
         * */
        beforeAdjustPopup:function (arg) {
            console.log('beforeAdjustPopup');
            if(!arg) return false;
            return true;
        },
        /**
         * 表单数据填充前
         * */
        beforeDataFill:function (data) {
            console.log('beforeDataFill',data);
        },
        /**
         * 请求流程数据成功时
         * */
        onProcessInstanceReady:function (result) {
            this.disabledInputs=[];
            var rawData=window.module.getRawFormData();
            if(!rawData) rawData={};
            //debugger
            if(result.data.approvalStatus!="approving") {

                for(var field in FORM_VIEW) {
                    //debugger
                    var input = $("#" + field);
                    if(rawData[field]==null) {
                        input.parents(".layui-form-item").hide();
                    }
                    this.disableInput(input);
                }
                window.module.adjustPopup(1);
                return;
            }

            // 隐藏全部先
            this.hideAllFormItems();

            // debugger
            // 可根据流程状态、当前审批节点判断和控制表单页面
            processInstance=result.data;
            console.log("processInstance",processInstance)
            // 获得所有待办节点
            var todoNodes=bpm.getTodoNodes(processInstance);
            for (var i = 0; i < todoNodes.length; i++) {
                var nodeId=todoNodes[i].camundaNodeId;
                var isMyTodoNode=bpm.isCurrentUserTodoNode(processInstance,nodeId);

                for(var field in FORM_VIEW) {
                    var selector=FORM_VIEW[field]["selector"];
                    var input=null;
                    if(selector==null) {
                        input=$("#" + field);
                    } else {
                        input=selector();
                    }
                    // 处理显示问题
                    if(FORM_VIEW[field].display===true) {
                        input.parents(".layui-form-item").show();
                        this.removeFromDisabledInputs(input.attr("name"));
                    } else if(FORM_VIEW[field].display===false){
                        input.parents(".layui-form-item").hide();
                    }
                    if(typeof(FORM_VIEW[field].display)=='function'){
                        //debugger
                        var display=FORM_VIEW[field].display(nodeId,rawData);
                        if(display) {
                            input.parents(".layui-form-item").show();
                            this.removeFromDisabledInputs(input.attr("name"));
                        } else {
                            input.parents(".layui-form-item").hide();
                        }
                    }
                    else {
                        for(var j=0;j<FORM_VIEW[field].display.length;j++) {
                            if(nodeId==FORM_VIEW[field].display[j]) {
                                input.parents(".layui-form-item").show();
                                this.removeFromDisabledInputs(input.attr("name"));
                            }
                        }
                    }


                    // 处理可编辑性
                    if(FORM_VIEW[field].readonly===true) {
                       this.disableInput(input);
                    } else if(FORM_VIEW[field].readonly===false){
                        // $("#"+field).attr("readonly", "yes");
                    } else if(typeof(FORM_VIEW[field].readonly)=='function'){
                        //debugger
                        var ro=FORM_VIEW[field].readonly(nodeId);
                        if(ro) {
                            this.disableInput(input);
                        } else {
                            // 如果不是当前账户的待办节点
                            if(!isMyTodoNode) {
                                this.disableInput(input);
                            }
                        }
                    } else {
                        for(var j=0;j<FORM_VIEW[field].readonly.length;j++) {
                            // 如果输入框在当前节点被指定为只读
                            if(nodeId==FORM_VIEW[field].readonly[j]) {
                                this.disableInput(input);
                            } else {
                                // 如果不是当前账户的待办节点
                                if(!isMyTodoNode) {
                                    this.disableInput(input);
                                }
                            }
                        }
                    }
                }

                window.module.adjustPopup(1);


            }

            // 按表单数据再调整一次
            this.adjustFormItemsForNode(todoNodes[0], bpm.isCurrentUserTodoNode(processInstance,todoNodes[0]));

            console.log("todoNodes",todoNodes);
            // 判断是否为待办节点
            var isTodoNode=bpm.isTodoNodes(processInstance,"N1");
            console.log("isTodoNode:N1",isTodoNode);
            // 判断是否为当前账户的待办节点
            var isMyTodoNode=bpm.isCurrentUserTodoNode(processInstance,"N1");
            console.log("isMyTodoNode:N1",isMyTodoNode);
        },
        adjustFormItemsForNode(nodeId,isMyTodoNode) {

            var data=window.module.getFormData();
            var value=data.isGotBase;
            //debugger
            if(nodeId="N1") {

                if(value=="1") {
                    $("#caseAgentIds").parents(".layui-form-item").show();
                    $("#outPersonIds").parents(".layui-form-item").hide();
                } else {
                    $("#caseAgentIds").parents(".layui-form-item").hide();
                    $("#outPersonIds").parents(".layui-form-item").show();
                }
            }

        },
        disabledInputs:[],
        removeFromDisabledInputs(name) {
            var tmp=[];
            for (var i = 0; i < this.disabledInputs.length; i++) {
                if(this.disabledInputs[i]==name) continue;
                tmp.push(this.disabledInputs[i]);
            }
            this.disabledInputs=tmp;
        },
        disableInput(input) {
            var name=input.attr("name");
            // if(name=="subtype") {
            //     debugger;
            // }
            this.disabledInputs.push(name);
            var inputType=input.attr("input-type");
            var button=$("#"+name+"-button");
            fox.disableButton(button,true);
            input.attr("readonly", "yes");
            input.attr("disabled", "yes");
            // fm.find("input[type=checkbox]").attr("disabled", "yes");
            if(inputType=="switch") {
                var el=input.parent().find(".layui-form-switch");
                el.addClass("layui-disabled");
                el.addClass("layui-checkbox-disabled");
                el.addClass("layui-form-switch-disabled");
            }
        },
        /**
         * 请求流程数据错误时
         * */
        onProcessInstanceError:function (result) {
            return true;
        },
        /**
         * 表单数据填充后
         * */
        afterDataFill:function (data) {
            console.log('afterDataFill',data);
        },
        /**
         * 对话框打开之前调用，如果返回 null 则不打开对话框
         * */
        beforeDialog:function (param){
            //param.title="覆盖对话框标题";
            return param;
        },
        /**
         * 对话框回调，表单域以及按钮 会自动改变为选中的值，此处处理额外的逻辑即可
         * */
        afterDialog:function (param,result) {
            console.log('dialog',param,result);
        },
        /**
         * 当下拉框别选择后触发
         * */
        onSelectBoxChanged:function(id,selected,changes,isAdd) {
            console.log('onSelectBoxChanged',id,selected,changes,isAdd);
        },
        /**
         * 当日期选择组件选择后触发
         * */
        onDatePickerChanged:function(id,value, date, endDate) {
            console.log('onDatePickerChanged',id,value, date, endDate);
        },
        onRadioBoxChanged:function(id,data,checked) {
            console.log('onRadioChanged',id,data,checked);
        },
        onCheckBoxChanged:function(id,data,checked) {
            console.log('onCheckBoxChanged',id,data,checked);
        },

        /**
         * 在流程提交前处理表单数据
         * */
        processFormData4Bpm:function(processInstanceId,param,callback) {
            // 设置流程变量，并通过回调返回
            // debugger
            var data=window.module.getFormData();
            if(!window.module.verifyForm(data)) return;
            for (var i = 0; i < this.disabledInputs.length; i++) {
                data[this.disabledInputs[i]]=null;
            }
            window.module.saveForm(data,function (data,action){
                var variables={};
                // 此回调是必须的，否则流程提交会被中断
                callback(variables);
            });
        },
        /**
         * 数据提交前，如果返回 false，停止后续步骤的执行
         * */
        beforeSubmit:function (data) {
            console.log("beforeSubmit",data);
            return true;
        },
        /**
         * 数据提交后窗口关闭前，如果返回 false，停止后续步骤的执行
         * */
        betweenFormSubmitAndClose:function (param,result) {
            console.log("betweenFormSubmitAndClose",result);
            return true;
        },
        /**
         * 数据提交后执行
         * */
        afterSubmit:function (param,result) {
            console.log("afterSubmitt",param,result);
        },

        /**
         * 文件上传组件回调
         *  event 类型包括：
         *  afterPreview ：文件选择后，未上传前触发；
         *  afterUpload ：文件上传后触发
         *  beforeRemove ：文件删除前触发
         *  afterRemove ：文件删除后触发
         * */
        onUploadEvent: function(e) {
            console.log("onUploadEvent",e);
        },
        /**
         * 末尾执行
         */
        ending:function() {

        }
    }
    //
    window.pageExt={form:form,list:list};
});
